<?php
/**
 * XmuSlh, web platform of Student Association Federation of Xiamen University
 * 
 * Rewritting one or some pages of StatusNet. 
 * To get the original version, please visit <http://status.net/>.
 * 
 * StatusNet, the distributed open-source microblogging tool
 * 
 * LICENCE: This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

/**
 * 添加一个图片到相应的相册.
 * 
 * @author		ytukie <ytukie@gmail.com>
 * @version		0.2
 * 
 * 0.2)  Inherited from Addaction.
 */

// XmuSlh only.
if ( !defined('XMUSLH')) { exit(1); }

// Requirements.
require_once INSTALLDIR . '/lib/slh_addaction.php';
require_once INSTALLDIR . '/lib/slh_rights.php';

require_once INSTALLDIR . '/widgets/slh_form_addphoto.php';
require_once INSTALLDIR . '/widgets/slh_form_addphotonews.php';

require_once INSTALLDIR . '/classes/PhotoSet.php';
require_once INSTALLDIR . '/classes/Photo.php';


class AddphotoAction extends AddAction
{
	/**
	 * The id of the photoset.
	 */
	var $photoset_id = null;
	
	function title()
	{
		return '添加相片';
	}
	
	function prepare($args)
	{
		if ( !Rights::hasRight(slh_get_userrights(), RIGHT_PHOTOSET)) {
			return false;
		}
		
		parent::prepare($args);
		
		// Get the photoset_id.
		$this->photoset_id = $this->getTrimmedArg('gphotoset_id');
		
		if (empty($this->photoset_id)) {
			$this->clientError('没有这个相册呃.');
		} else if ( !PhotoSet::hasId($this->photoset_id)) {
			$this->clientError('没有找到这个相册呃.');
		}
		
		return true;
	}
	
	/**
	 * Shows the guidance.
	 * Overriding.
	 */
	function showGuidance()
	{
		// Html code here.
		$this->element('h3', null, '添加图片哈');
		
		$this->instruction('呃,说明下添加的具体是什么东东,怎么添加好了.');
		
		// If added successfully, then?
		if ($this->added) {
			$this->element('p', 'cls_p_success', '添加成功!');
			// Or show a nav.
		}
	}
	
	/**
	 * Shows the widgets like form, or etc.
	 * Overriding.
	 */
	function showForm()
	{
		$form = new AddphotoForm($this, $this->args);
		$form->show();
		
		// Show it if add successfully.
		if ($this->added) {
			$form = new AddphotonewsForm($this, $this->args);
			$form->show();
		}
	}	
	
	
	/**
	 * Try to add the data into the database.
	 */
	function tryAdd()
	{
		// CSRF protection and Refreshing-post protection.
		$this->checkSessionToken();
		
		// Workaround for PHP returning empty $_POST and $_FILES when POST
		// length > post_max_size in php.ini
		if (empty($_FILES) &&
			empty($_POST) &&
			($_SERVER['CONTENT_LENGTH'] > 0)) {
			$msg = 'The server was unable to handle that mush POST data due to its current configuration.';
			$this->showAction($msg);
			return;
		}
		
		// The 'input file' name.
		// FIXME: Local variables?
		$photofilenames = array('photofile_a',
								'photofile_b',
								'photofile_c',
								'photofile_d',
								'photofile_e');
		
		$photofiles = array();
		
// FIXME: Remove the $_FILES, use ->name and ->size class variables instead.
		foreach ($photofilenames as $id) {
			// Validate the file first.
			if ( !empty($_FILES[$id]['name'])) {
				
				if (empty($_FILES[$id]['tmp_name'])) {
					$this->showAction($_FILES[$id]['name'] . '不符合要求, 请重新选择上传的文件.');
					return;
				}
				
				try {
					$photofiles[$id] = ImageFile::fromUpload($id);
				} catch (Exception $e) {
					$this->showAction($_FILES[$id]['name'] . ': ' . $e->getMessage());
					return;
				}
				
				if (null === $photofiles[$id] ||
					intval($_FILES[$id]['size']) > ImageFile::maxPhotoSizeInt()) {
					$this->showAction($_FILES[$id]['name'] . '不符合要求, 请重新选择上传的文件.');
					return;
				}
			}
		}
		
		// All the photos have successfully uploaded to the tmp files.
		if (empty($photofiles)) {
			$this->showAction('没有图片被选中.');
			return;
		} else {
			foreach ($photofiles as $id => $photofile) {
				$mimetype = $photofile->preferredType();
				$filename = Photo::filename($this->photoset_id, 
											image_type_to_extension($mimetype),
											uniqid());
				$filepath = Photo::path($filename);
				$photofile->copyTo($filepath);
				
				// Add an thumbnail.
				$thumbnailpath = Photo::path(Photo::filename2Thumbnailname($filename));
				$photofile->photoResize($thumbnailpath, 
										PHOTO_THUMBNAIL_MAXWIDTH,
										PHOTO_THUMBNAIL_MAXHEIGHT);
				
				// Adds into the database.
				$photo_id = Photo::add(array('photoset_id' => $this->photoset_id,
											 'photoname' => $filename,
											 'mimetype' => $mimetype,
											 'width' => $photofile->width,
											 'height' => $photofile->height));
				
				if ( !$photo_id) {
					$msg = '添加' . 
						   $_FILES[$id]['name']
						    . '失败, 请重新尝试添加' . 
						   $_FILES[$id]['name']
						   . '以及之后的图片.';
					$this->showAction($msg);
					
					// Delete the uploaded file.
					@unlink($filepath);
					@unlink($thumbnailpath);
					
					// For post again.
					$this->unsetSessionToken();
					return;
				}
			}
			
			// TODO: Update the count of the photo set.
			
			// Success.
			// Unset the seesion token preventing post-again.
			$this->unsetSessionToken();
			
			$this->added = true;
			$this->showAction();
		}
	}
}

?>